package service

import (
	"errors"
	"gitee.com/CrazyMage/blog-service/global"
	"gitee.com/CrazyMage/blog-service/pkg/upload"
	"mime/multipart"
	"os"
)

type FileInfo struct {
	Name      string
	AccessUrl string
}

/*
fileType 文件类型枚举（如图片/文档）
file 文件内容流
fileHeader 文件头信息
*/
func (svc *Service) UploadFile(fileType upload.FileType, file multipart.File, fileHeader *multipart.FileHeader) (*FileInfo, error) {
	fileName := upload.GetFileName(fileHeader.Filename) // 获取处理后的文件名
	if !upload.CheckContainExt(fileType, fileName) {    // 检查文件后缀
		return nil, errors.New("file suffix is not supported.")
	}
	if upload.CheckMaxSize(fileType, file) { // 检查文件大小
		return nil, errors.New("exceeded maximum file limit.")
	}

	uploadSavePath := upload.GetSavePath()    // 获取存储路径
	if upload.CheckSavePath(uploadSavePath) { // 检查路径是否存在,如果不存在则创建
		if err := upload.CreateSavePath(uploadSavePath, os.ModePerm); err != nil { //创建保存目录
			return nil, errors.New("failed to create save directory.")
		}
	}
	if upload.CheckPermission(uploadSavePath) { // 检查写入权限
		return nil, errors.New("insufficient file permissions.")
	}

	dst := uploadSavePath + "/" + fileName                   // 拼接完整存储路径
	if err := upload.SaveFile(fileHeader, dst); err != nil { // 保存文件
		return nil, err
	}

	accessUrl := global.AppSetting.UploadServerUrl + "/" + fileName
	return &FileInfo{
		Name:      fileName,  // 存储的文件名
		AccessUrl: accessUrl, // 完整访问URL
	}, nil
}
